package com.xzz.string;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author: hhz
 * @create: 2022-01-06 16:44
 * 71. 简化路径
 **/
public class SimplifyPath {
    public static void main(String[] args) {
        System.out.println(simplifyPath("/home/"));
        System.out.println(simplifyPath("/../"));
        System.out.println(simplifyPath("/home//foo/"));
        System.out.println(simplifyPath("/a/./b/../../c/"));
        System.out.println(simplifyPath("/a/../../b/../c//.//"));
        System.out.println(simplifyPath("/a//b////c/d//././/.."));
    }
    public static String simplifyPath(String path) {
        StringBuilder sb = new StringBuilder("/");
        Deque<String> stack = new ArrayDeque<>();
        String[] split = path.split("/");
        for (String s : split) {
            if(s.equals("..") ){
                if( !stack.isEmpty()){
                    stack.pollLast();
                }
            }else if(s.equals(".") || s.equals("")){
                continue;
            }else {
                stack.offerLast(s);
            }
        }
        while (!stack.isEmpty()){
            sb.append(stack.pollFirst());
            sb.append("/");
        }
        String s = sb.toString();
        return s.length()==1?s:s.substring(0,s.length()-1);
    }
}
